<?php
namespace app\facility\logic;

use think\Model;
use think\Db;
use think\Cache;
use Grafika\Grafika;
use OSS\OssClient;
use OSS\Core\OssException;

class Camera extends Model
{
    public function compare_img($new_file = '', $ossId = '', $receiver = '', array $user_info)
    {
        $thum_vista_img = $user_info['thum_vista_img'] ? $user_info['thum_vista_img'] : '';
        
    	$time = time();
    	$six_startclock = strtotime("18:00");
    	$six_endclock = strtotime("6:00, +24 hours");
    	if ($time >= $six_startclock && $time <= $six_endclock) {
    		$imgId = '';
    	} else {
    		$imgId = $user_info['standard_img_id'] ? $user_info['standard_img_id'] : '';
    	}
    	if ($user_info['is_monitor'] == 1) {
    		$end_colck = strstr($user_info['end_time'], ':', true);
	    	$begin_time = strtotime("{$user_info['begin_time']}");
	    	$end_time = ($end_colck <= 12 && $end_colck >= 0) ? strtotime("{$user_info['end_time']}, +24 hours") : strtotime("{$user_info['end_time']}");
	    	if ($time >= $begin_time && $time <= $end_time) {
	    		$imgId = $user_info['night_img_id'] ? $user_info['night_img_id'] : '';
	    	} 
    	}
    	// dump($imgId);
    	if (empty($imgId)) {
    		$data = ['img_id'=>$ossId, 'standard_img_id'=>$thum_vista_img, 'type'=>1, 'add_time'=>date('Y-m-d H:i:s'), 'billboard_id'=>$user_info['pid'], 'error_code'=>100];
	    	Db::table('shooting_record')->insert($data);
	    	// 保存缓存查询监测画面状态
            Cache::set("img_billboard_" . $user_info['pid'], array('type'=>1));
    		return 'no';
    	}
    	$ossInfo = Db::table('aliyun_oss')->where('id', $imgId)->field('id, name, path')->find();
    	$standard_file = APP_ROOT_PATH . $ossInfo['path'] . $ossInfo['name'];

    	if (!file_exists($standard_file)) {
	        $accessKeyId = config('accessKeyId');
	        $accessKeySecret = config('accessKeySecret');
	        $endpoint = config('endpoint');
	        $bucket= config('bucket');

	        $object = $ossInfo['name'];
	        $path1 = "/static/camimg/" . date('Ymd', time()) . "/";
	        $download_file = APP_ROOT_PATH . $path1;
	        if (!file_exists($download_file)) {
	        //检查是否有该文件夹，如果没有就创建，并给予最高权限
	            mkdir($download_file, 0700);
	        }
	        $download_file .= $ossInfo['name'];
	        $options = array(
	            OssClient::OSS_FILE_DOWNLOAD => $download_file,
	        );
	        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
	        try{
	            $ossClient->getObject($bucket, $object, $options);
	            Db::table('aliyun_oss')->where('id', $imgId)->update(['path' => $path1]);
	            $standard_file = $download_file;
	        } catch(OssException $e) {
	            $standard_file = '';
	        }
	    }
	    if ($standard_file == '') {
	    	$data = ['img_id'=>$ossId, 'standard_img_id'=>$thum_vista_img, 'type'=>1, 'add_time'=>date('Y-m-d H:i:s'), 'billboard_id'=>$user_info['pid'], 'error_code'=>100];
	    	Db::table('shooting_record')->insert($data);
	    	// 保存缓存查询监测画面状态
            Cache::set("img_billboard_" . $user_info['pid'], array('type'=>1));
	    	return 'no';
	    }
        $editor = Grafika::createEditor();
        $result = $editor->compare($standard_file, $new_file);
        // dump($result);
        if ($result >= 0 && $result < 10) {
        	// 正常
        	$data = ['img_id'=>$ossId, 'standard_img_id'=>$thum_vista_img, 'type'=>1, 'add_time'=>date('Y-m-d H:i:s'), 'billboard_id'=>$user_info['pid'], 'error_code'=>100];
        	// $sendUrl = ['type'=>'201','error_code'=>'100','msgContent'=>"{$user_info['bname']}".'-画面正常'];
        	// 保存缓存查询监测画面状态
            Cache::set("img_billboard_" . $user_info['pid'], array('type'=>1));
        } elseif ($result >= 10 && $result < 20) {
        	// 画面破损
        	$data = ['img_id'=>$ossId, 'standard_img_id'=>$thum_vista_img, 'type'=>2, 'add_time'=>date('Y-m-d H:i:s'), 'billboard_id'=>$user_info['pid'], 'error_code'=>103];
        	$sendUrl = ['type'=>'201','error_code'=>'102','msgContent'=>"{$user_info['bname']}".'-画面不符'];
        	// 设置设备状态
        	Db::table('billboard')->where('id', $user_info['pid'])->update(['state'=>0]);
        	$update_bil = Cache::get("update_billboard_" . $user_info['pid']);
        	if ($update_bil) {
        		$update_bil['device_type'] = 2;
        		Cache::set("update_billboard_" . $user_info['pid'], $update_bil);
        	}
        	// 保存缓存查询监测画面状态
            Cache::set("img_billboard_" . $user_info['pid'], array('type'=>2));
        } elseif ($result >= 20) {
        	if ($time >= $six_startclock && $time <= $six_endclock) {
        		// 不亮灯
        		$data = ['img_id'=>$ossId, 'standard_img_id'=>$thum_vista_img, 'type'=>2, 'add_time'=>date('Y-m-d H:i:s'), 'billboard_id'=>$user_info['pid'], 'error_code'=>101];
        		$sendUrl = ['type'=>'201','error_code'=>'101','msgContent'=>"{$user_info['bname']}".'-不亮灯'];
        	} else {
        		// 画面不符
        		$data = ['img_id'=>$ossId, 'standard_img_id'=>$thum_vista_img, 'type'=>2, 'add_time'=>date('Y-m-d H:i:s'), 'billboard_id'=>$user_info['pid'], 'error_code'=>103];
        		$sendUrl = ['type'=>'201','error_code'=>'103','msgContent'=>"{$user_info['bname']}".'-画面不符'];
        	}
        	// 设置设备状态
        	Db::table('billboard')->where('id', $user_info['pid'])->update(['state'=>0]);
        	$update_bil = Cache::get("update_billboard_" . $user_info['pid']);
        	if ($update_bil) {
        		$update_bil['device_type'] = 2;
        		Cache::set("update_billboard_" . $user_info['pid'], $update_bil);
        	}
        	// 保存缓存查询监测画面状态
            Cache::set("img_billboard_" . $user_info['pid'], array('type'=>2));
        }
        // dump($data);
        // dump(Cache::get("update_billboard_" . $user_info['pid']));
        Db::table('shooting_record')->insert($data);
        if (isset($sendUrl)) {
    	    $url = "http://39.108.178.245:55151/PushMsg.php?recevicers=".$receiver."&content=".json_encode($sendUrl);
	        $result = https_request($url);
        }
        // dump($result);
        // dump($sendUrl);
        return 'ok';
    }

    public function ossUpload($file_name, $new_file)
    {
        $accessKeyId = config('accessKeyId');
        $accessKeySecret = config('accessKeySecret');
        $endpoint = config('endpoint');
        $bucket= config('bucket');
        $object = $file_name;
        $filePath = $new_file;
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object, $filePath);
            return true;
        } catch (OssException $e) {
            return false;
        }
    }


    





}